package com.DJ.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dj.common.domain.UserVO;
import com.dj.common.dto.QueryDto;
import com.DJ.mapper.UserDao;
import com.DJ.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserVO> implements UserService {
    private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserDao userDao;

    //添加
    @Override
    public void insert(UserVO userVO) {
        userDao.insert(userVO);
        log.info("----info----:{}",userVO);
    }
    //删除
    @Override
    public void delete(Long id) {
        userDao.deleteById(id);
    }
    //修改
    @Override
    public void update(UserVO user) {
        userDao.updateById(user);
    }
    //查询单个
    @Override
    public UserVO get(Long id) {
        //根据Id查询
        UserVO user = userDao.selectById(id);
        return  user;
    }

    //分页查询
    @Override
    public Page<UserVO> getAll(QueryDto dto) {
        if (dto.getPageNum() == null && dto.getPageSize() == null){
            dto.setPageNum(1);
            dto.setPageSize(10);
        }
        //参数检查
        Page<UserVO> page = new Page<>(dto.getPageNum(),dto.getPageSize()); //获取分页页码

        LambdaQueryWrapper<UserVO> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (!StringUtils.isEmpty(dto.getAge())){
            lambdaQueryWrapper.eq(UserVO::getAge,dto.getAge());
        }
        if (!StringUtils.isEmpty(dto.getName())){
            lambdaQueryWrapper.eq(UserVO::getName,dto.getName());
        }
        //开启线程异步处理其他业务
        Thread t1 = new Thread() {
            public void run() {
                System.out.println("t1 start");
                for (int i = 0; i <1000; i++) {
                    System.out.println("加班中。。。");
                }
            }
        };
        //开启线程异步处理其他业务
        Thread t2 = new Thread() {
            public void run() {
                System.out.println("t2 start");
                for (int i = 0; i <1000; i++) {
                    System.out.println("摸鱼中。。。");
                }
            }
        };
        t1.start();
        t2.start();
        //page查询 页码，条件
        return page(page, lambdaQueryWrapper);
    }


    public void file(MultipartFile file) throws IOException {
        // 2. 文件上传的目录
        String fileDirPath = "D:/develop/code/code/image";
        File dirFile = new File(fileDirPath);
        // 判断文件目录是否存在
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        // 3.准备文件上传的全路径   :路径加文件名称
        String fileNmae = file.getOriginalFilename();  //文件名称.后缀
        File realFile = new File(fileDirPath+"/"+fileNmae);
        // 将字节信息输出到文件
            file.transferTo(realFile);
    }

    //
    @Override
    public void exportExcel(HttpServletRequest request) {
        ExportParams exportParams = new ExportParams("用户信息","用户信息表");

        List<UserVO> list = new ArrayList();
        List<UserVO> allUser = getAllUser();
        list.addAll(allUser);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, UserVO.class, list);
        try {
            FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop");
            workbook.write(fos);
            fos.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void importExcel(MultipartFile file)  {
        try {
           File tempfile = multipartFiletoFile(file);

            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            importParams.setHeadRows(1);
            assert tempfile != null;
            System.out.println(tempfile.getAbsolutePath());
            List<UserVO> list = ExcelImportUtil.importExcel(new FileInputStream(tempfile.getAbsolutePath()), UserVO.class, importParams);
            list.forEach(user->insert(user));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    //multipartFile转File
    private File multipartFiletoFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private List<UserVO> getAllUser() {
        List<UserVO> userList = baseMapper.selectList(null);
        return userList;
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        //裁判
        final CountDownLatch cdOrder = new CountDownLatch(1);
        //选手
        final CountDownLatch cdAnswer = new CountDownLatch(4);
        for (int i = 0; i < 4; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("选手" + Thread.currentThread().getName() + "正在等待裁判发布口令");
                        cdOrder.await();
                        System.out.println("选手" + Thread.currentThread().getName() + "已接受裁判口令");
                        Thread.sleep((long) (Math.random() * 10000));
                        System.out.println("选手" + Thread.currentThread().getName() + "到达终点");
                        cdAnswer.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        try {
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println("裁判"+Thread.currentThread().getName()+"即将发布口令");
            cdOrder.countDown();
            System.out.println("裁判"+Thread.currentThread().getName()+"已发送口令，正在等待所有选手到达终点");
            cdAnswer.await();
            System.out.println("所有选手都到达终点");
            System.out.println("裁判"+Thread.currentThread().getName()+"汇总成绩排名");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }
}
